﻿using System.Activities;
using System.Linq;
using System.ServiceProcess;
using log4net;

namespace Reactor.ServiceGrid.Workflows.Activities
{
    public class ObtainWindowsServiceController : CodeActivity<ServiceController>
    {
        [RequiredArgument]
        public InArgument<string> WindowsServiceName { get; set; }

        [RequiredArgument]
        public InArgument<ILog> Logger { get; set; }

        #region Overrides of CodeActivity<ServiceController>

        /// <summary>
        /// When implemented in a derived class, performs the execution of the activity.
        /// </summary>
        /// <returns>
        /// The result of the activity’s execution.
        /// </returns>
        /// <param name="context">The execution context under which the activity executes.</param>
        protected override ServiceController Execute(CodeActivityContext context)
        {
            var logger = context.GetValue(Logger);
            var serviceName = context.GetValue(WindowsServiceName);

            if(logger.IsDebugEnabled) logger.DebugFormat("Searching for ServiceController named: {0}", serviceName);
            
            var serviceController = ServiceController.GetServices().SingleOrDefault(s => s.ServiceName == serviceName);

            if(serviceController != null)
            {
                if(logger.IsDebugEnabled) 
                    logger.DebugFormat("Unable to locate ServiceController for service named: {0}", serviceName);
            }
            else
            {
                if (logger.IsDebugEnabled)
                    logger.DebugFormat("Located ServiceController for service named: {0}", serviceName);
            }

            return serviceController;
        }

        #endregion
    }
}
